/*
 * @Author: wangdazhuang
 * @Date: 2024-08-28 19:50:08
 * @LastEditTime: 2025-01-25 09:36:29
 * @LastEditors: wangdazhuang
 * @Description: 
 * @FilePath: /pornhub_app/lib/views/player/views/comment_list.dart
 */

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:pornhub_app/assets/styles.dart';
import 'package:pornhub_app/components/ad_banner/insert_ad.dart';
import 'package:pornhub_app/components/app_bg_view.dart';
import 'package:pornhub_app/components/circle_image.dart';
import 'package:pornhub_app/components/common_permission_alert.dart';
import 'package:pornhub_app/components/no_more/no_data.dart';
import 'package:pornhub_app/components/text_view.dart';
import 'package:pornhub_app/routes/routes.dart';
import 'package:pornhub_app/services/user_service.dart';
import 'package:pornhub_app/utils/color.dart';
import 'package:pornhub_app/utils/enum.dart';
import 'package:pornhub_app/utils/extension.dart';
import 'package:pornhub_app/views/player/views/comment_cell.dart';

import '../../../http/api/api.dart';
import '../../../http/http_service.dart';
import '../../../model/comment/comment_model.dart';

typedef CommentsType = int;

abstract class CommentTypeEnumValue {
  //播放器
  static const CommentsType player = 1;

  //短视频
  static const CommentsType short = 2;

  //新番预告
  static const CommentsType esploid = 3;

  //帖子评论
  static const CommentsType circle = 4;

  //咨询评论
  static const CommentsType infoPromotion = 5;

//播单
  static const CommentsType playList = 6;
}

class PlayCommentList extends StatefulWidget {
  final int? videoId;
  final int? episodeId;
  final int? dynamicId;
  final int? infoId;
  final CommentsType type;

// 针对短视频
  final int? commentCount;

  /// 播单
  final int? playlistId;

  const PlayCommentList({
    super.key,
    this.videoId,
    this.commentCount,
    required this.type,
    this.episodeId,
    this.dynamicId,
    this.infoId,
    this.playlistId,
  });

  @override
  State<StatefulWidget> createState() {
    return PlayerCommentsState();
  }
}

class PlayerCommentsState extends State<PlayCommentList> {
  int _page = 1;
  final _pageSize = 30;
  List<CommentModel> commentItems = [];
  bool requesting = false;
  final refreshController = EasyRefreshController();
  CommentModel? selectedItem;
  CommentModel? topModel;
  final controller = TextEditingController();
  final node = FocusNode();

  /// 刷新
  Future<IndicatorResult> onRefreshComments() async {
    _page = 1;
    if (widget.type == CommentTypeEnumValue.esploid) {
      final items = await Api.fetchEpisodeCommentList(
        page: _page,
        pageSize: 100,
        episodeId: widget.episodeId,
      );
      if (items != null) {
        commentItems = items;
        if (mounted) {
          setState(() {});
        }
        return IndicatorResult.success;
      }
      return IndicatorResult.none;
    }

    final params = widget.type == CommentTypeEnumValue.circle
        ? {"dynamicId": widget.dynamicId}
        : widget.type == CommentTypeEnumValue.infoPromotion
            ? {"infoId": widget.infoId ?? 0}
            : widget.type == CommentTypeEnumValue.playList
                ? {"playlistId": widget.playlistId ?? 0}
                : {"videoId": widget.videoId ?? 0};
    try {
      final s = await httpInstance.get(
        url: widget.type == CommentTypeEnumValue.circle
            ? "community/dynamic/commentList"
            : widget.type == CommentTypeEnumValue.infoPromotion
                ? "infoPromotion/commentList"
                : widget.type == CommentTypeEnumValue.infoPromotion
                    ? 'playlist/commentList'
                    : "video/commentList",
        queryMap: {
          "page": _page,
          "pageSize": _pageSize,
          ...params,
        },
        complete: CommentModel.fromJson,
      );
      if (s is List<CommentModel> == false) {
        return IndicatorResult.fail;
      }
      commentItems = s;
      if (mounted) {
        setState(() {});
      }
      if (s.isEmpty) {
        return IndicatorResult.none;
      }
      return IndicatorResult.success;
    } catch (_) {
      return IndicatorResult.fail;
    }
  }

  // 上拉加载更多
  Future<IndicatorResult> onLoadComments() async {
    /// 新番评论
    if (widget.type == CommentTypeEnumValue.esploid) {
      _page++;
      final items = await Api.fetchEpisodeCommentList(
        page: _page,
        pageSize: 100,
        episodeId: widget.episodeId,
      );
      if (items != null && items.isNotEmpty) {
        commentItems.addAll(items);
        if (mounted) {
          setState(() {});
        }
        return IndicatorResult.success;
      }
      return IndicatorResult.noMore;
    }

    try {
      _page = _page + 1;
      final params = widget.type == CommentTypeEnumValue.circle
          ? {"dynamicId": widget.dynamicId}
          : widget.type == CommentTypeEnumValue.infoPromotion
              ? {"infoId": widget.infoId ?? 0}
              : widget.type == CommentTypeEnumValue.playList
                  ? {"playlistId": widget.playlistId ?? 0}
                  : {"videoId": widget.videoId ?? 0};
      final s = await httpInstance.get(
        url: widget.type == CommentTypeEnumValue.circle
            ? "community/dynamic/commentList"
            : widget.type == CommentTypeEnumValue.infoPromotion
                ? "infoPromotion/commentList"
                : widget.type == CommentTypeEnumValue.infoPromotion
                    ? "playlist/commentList"
                    : "video/commentList",
        queryMap: {
          ...params,
          "page": _page,
          "pageSize": _pageSize,
        },
        complete: CommentModel.fromJson,
      );
      if (s is List<CommentModel> == false) {
        return IndicatorResult.fail;
      }
      commentItems.addAll(s);
      if (mounted) {
        setState(() {});
      }
      if (s.isEmpty) {
        return IndicatorResult.noMore;
      }
      return IndicatorResult.success;
    } catch (_) {
      return IndicatorResult.fail;
    }
  }

  addURL(CommentsType type) {
    if (type == CommentTypeEnumValue.esploid) {
      return 'episode/saveComment';
    }
    if (type == CommentTypeEnumValue.circle) {
      return 'community/dynamic/saveComment';
    }
    if (type == CommentTypeEnumValue.infoPromotion) {
      return 'infoPromotion/saveComment';
    }
    if (type == CommentTypeEnumValue.playList) {
      return 'playlist/saveComment';
    }
    return 'video/saveComment';
  }

  // 添加评论
  Future addComments(String content) async {
    if (requesting) {
      return;
    }
    requesting = true;
    try {
      final params = widget.type == CommentTypeEnumValue.esploid
          ? {"episodeId": widget.episodeId}
          : widget.type == CommentTypeEnumValue.circle
              ? {"dynamicId": widget.dynamicId}
              : widget.type == CommentTypeEnumValue.infoPromotion
                  ? {"infoId": widget.infoId}
                  : widget.type == CommentTypeEnumValue.playList
                      ? {"playlistId": widget.playlistId ?? 0}
                      : {"videoId": widget.videoId};

      final s = await httpInstance.post(
          url: addURL(widget.type),
          body: {
            ...params,
            "content": content,
            "topId": topModel?.commentId ?? 0,
            "parentId": selectedItem?.commentId ?? 0,
          },
          complete: CommentModel.fromJson);
      requesting = false;
      SmartDialog.showToast("评论成功,请等待审核!", alignment: Alignment.center);
      if (s is CommentModel == false) {
        reset();
        return;
      }
      if (topModel != null && selectedItem != null) {
        CommentModel some =
            commentItems.firstWhere((e) => e.commentId == topModel!.commentId);
        some.replyNum += 1;
        some.replyItems?.add(s);
      } else {
        if (commentItems.isEmpty) {
          commentItems.add(s);
        } else {
          commentItems.insert(0, s);
        }
      }
      reset();
    } catch (_) {
      requesting = false;
      reset();
    }
  }

  void reset() {
    selectedItem = null;
    topModel = null;
    controller.text = "";
    node.unfocus();
    if (mounted) {
      setState(() {});
    }
  }

  Future likeCommentAction(CommentModel m) async {
    ///点赞
    if (requesting) {
      return;
    }
    requesting = true;

    ///新番预告
    if (widget.type == CommentTypeEnumValue.esploid) {
      final r = await Api.toogleEpisodeCommentLike(m.commentId, like: m.isLike);
      requesting = false;
      if (r != null && r) {
        m.isLike = !m.isLike;
        if (m.isLike) {
          m.fakeLikes = m.fakeLikes + 1;
        } else {
          m.fakeLikes = m.fakeLikes - 1;
        }
        if (mounted) {
          setState(() {});
        }
      }
      return;
    }

    ///社区
    if (widget.type == CommentTypeEnumValue.circle) {
      final r = await Api.toogleDynamicCommentLike(m.commentId, like: m.isLike);
      requesting = false;
      if (r != null && r) {
        m.isLike = !m.isLike;
        if (m.isLike) {
          m.fakeLikes = m.fakeLikes + 1;
        } else {
          m.fakeLikes = m.fakeLikes - 1;
        }
        if (mounted) {
          setState(() {});
        }
      }
      return;
    }

    // ///成人资讯
    // if (widget.type == CommentTypeEnumValue.infoPromotion) {
    //   final r = await Api.toogleInfocCommentLike(m.commentId, like: m.isLike);
    //   requesting = false;
    //   if (r != null && r) {
    //     m.isLike = !m.isLike;
    //     if (m.isLike) {
    //       m.fakeLikes = m.fakeLikes + 1;
    //     } else {
    //       m.fakeLikes = m.fakeLikes - 1;
    //     }
    //     if (mounted) {
    //       setState(() {});
    //     }
    //   }
    //   return;
    // }

    //长短视频
    final r =
        await Api.likeVideoComment(toLike: !m.isLike, commentId: m.commentId);
    requesting = false;
    if (r) {
      m.isLike = !m.isLike;
      if (m.isLike) {
        m.fakeLikes = m.fakeLikes + 1;
      } else {
        m.fakeLikes = m.fakeLikes - 1;
      }
      if (mounted) {
        setState(() {});
      }
    }
  }

  _buildCommentList() {
    return SliverPadding(
      padding: EdgeInsets.symmetric(horizontal: 14.w, vertical: 12.w),
      sliver: commentItems.isEmpty
          ? SizedBox(
              width: Get.width,
              height: 250.w,
              child: const Center(child: NoData()),
            ).sliver
          : SliverList.builder(
              itemCount: commentItems.length,
              itemBuilder: (context, index) {
                return CommentCell(
                  type: widget.type,
                  videoId: widget.videoId,
                  esplodId: widget.episodeId,
                  dynamicId: widget.dynamicId,
                  infoId: widget.infoId,
                  playlistId: widget.playlistId,
                  model: commentItems[index],
                  tap: (v) {
                    /// 回复
                    selectedItem = v;
                    topModel = v;
                    node.requestFocus();
                    if (mounted) {
                      setState(() {});
                    }
                  },
                  tapList: (m, m1) {
                    //m是顶层 m1是parent
                    selectedItem = m1;
                    topModel = m;
                    if (mounted) {
                      setState(() {});
                    }
                  },
                  likeLelvel1: (m) {
                    likeCommentAction(m);
                  },
                  likeLevel2: (m, m1) {
                    likeCommentAction(m1);
                  },
                );
              },
            ),
    );
  }

  @override
  void initState() {
    super.initState();
    onRefreshComments();
    node.addListener(
      () {
        if (node.hasFocus && Get.find<UserService>().isVIP == false) {
          node.unfocus();
          permission_alert(
            Get.context!,
            desc: "会员才能评论哟!",
            okAction: () {
              Get.toNamed(Routes.vip);
            },
          );
          return;
        }
      },
    );
  }

  ///添加评论
  void sendAction() {
    if (controller.text.isEmpty) {
      node.unfocus();
      selectedItem = null;
      topModel = null;
      controller.text = "";
      setState(() {});
      return;
    }
    addComments(controller.text);
  }

  _buildTxtReply() {
    return SizedBox(
      height: 34.w,
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          CircleImage.network(Get.find<UserService>().user.logo!, size: 34.w),
          Container(width: 1.w, height: 18.w, color: COLOR.color_999999)
              .marginOnly(left: 12.w, right: 4.w),
          Expanded(
            child: SizedBox(
              height: 34.w,
              width: double.infinity,
              child: TextField(
                cursorHeight: 20.w,
                focusNode: node,
                controller: controller,
                textAlignVertical: TextAlignVertical.center,
                textInputAction: TextInputAction.done,
                onEditingComplete: () {
                  node.unfocus();
                  sendAction();
                },
                cursorColor: COLOR.color_999999,
                decoration: InputDecoration(
                    hintText: selectedItem == null
                        ? "快来说说你的感想吧"
                        : '回复@${selectedItem!.nickName}',
                    hintStyle: kTextStyle(COLOR.color_999999, fontsize: 14.w),
                    focusedBorder: InputBorder.none,
                    contentPadding: EdgeInsets.only(bottom: 14.w),
                    border: InputBorder.none,
                    labelStyle: kTextStyle(Colors.black, fontsize: 15.w)),
              ),
            ),
          ),
        ],
      ),
    ).paddingHorizontal(14.w).paddingTop(12.w);
  }

  _buildShortHeader() {
    final isCircle = widget.type == CommentTypeEnumValue.circle ||
        widget.type == CommentTypeEnumValue.infoPromotion;
    return isCircle
        ? Row(
            children: [
              TextView(
                text: '评论 ${commentItems.length}',
                color: COLOR.white,
                fontSize: 14.w,
              ).marginOnly(left: 14.w),
            ],
          )
        : Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              SizedBox(width: 18.w, height: 18.w),
              Text("全部${widget.commentCount ?? 0}条评论",
                  style: kTextStyle(COLOR.color_333333,
                      fontsize: 16.w, weight: FontWeight.w500)),
              Icon(
                Icons.cancel_rounded,
                size: 18.w,
                color: COLOR.color_666666,
              ).onTap(() {
                Get.back();
              }),
            ],
          ).paddingOnly(left: 14.w, top: 18.w, right: 14.w, bottom: 8.w);
  }

  _buildShortReplyTxt() {
    final isShort = widget.type == CommentTypeEnumValue.short;
    return Container(
      width: double.infinity,
      padding:
          EdgeInsets.only(top: 14.w, bottom: kIsWeb?37.w:14.w, left: 14.w, right: 14.w),
      decoration: BoxDecoration(
          color: isShort ? Colors.white : COLOR.hexColor('#000'),
          border: Border(
              top: BorderSide(
                  color: isShort
                      ? COLOR.hexColor('#eee')
                      : COLOR.hexColor('#1B1B1B')))),
      child: Row(
        children: [
          Expanded(
            child: Container(
                height: 40.w,
                width: 372.w,
                padding: EdgeInsets.symmetric(horizontal: 14.w),
                decoration: BoxDecoration(
                    color: isShort
                        ? COLOR.hexColor("#E9E9E9")
                        : COLOR.hexColor("#222222"),
                    borderRadius: BorderRadius.circular(20.w)),
                child: SizedBox(
                  height: 44.w,
                  width: double.infinity,
                  child: TextField(
                    cursorHeight: 20.w,
                    focusNode: node,
                    controller: controller,
                    textAlignVertical: TextAlignVertical.center,
                    textInputAction: TextInputAction.done,
                    onEditingComplete: () {
                      node.unfocus();
                      sendAction();
                    },
                    style: kTextStyle(isShort ? Colors.black : Colors.white),
                    cursorColor: COLOR.color_999999,
                    decoration: InputDecoration(
                      hintText: selectedItem == null
                          ? "写下你的评论..."
                          : '回复@${selectedItem!.nickName}',
                      hintStyle: kTextStyle(COLOR.color_999999, fontsize: 14.w),
                      focusedBorder: InputBorder.none,
                      contentPadding: EdgeInsets.only(bottom: 10.w),
                      border: InputBorder.none,
                      labelStyle: kTextStyle(Colors.black, fontsize: 15.w),
                    ),
                  ),
                ).marginHorizontal(4.w)),
          ),
          10.horizontalSpace,
          AppBgView(
            width: 80.w,
            height: 38.w,
            radius: 19.w,
            backgroundColor: COLOR.color_FF9000,
            text: "发布",
            textColor: COLOR.black,
            textSize: 14.w,
            onTap: () {
              node.unfocus();
              sendAction();
            },
          )
        ],
      ),
    );
  }

  Widget _buildAds() {
    return InsertAd(
      adress: AdPlaceNameEnum.PLAY_WIDGET,
      height: 120.w,
      margin: EdgeInsets.only(bottom: 40.w),
    );
  }

  Widget _buildTips() {
    return Container(
      alignment: Alignment.center,
      margin: EdgeInsets.symmetric(vertical: 10.w),
      child: Text.rich(TextSpan(children: [
        TextSpan(
            text: '*部分地区若遇视频无法播放，请尝试切换',
            style: TextStyle(color: Colors.white, fontSize: 12.w)),
        TextSpan(
            text: '移动网络或开VPN',
            style: TextStyle(color: COLOR.hexColor('#B93FFF'), fontSize: 12.w)),
      ])),
    );
  }

  @override
  Widget build(BuildContext context) {
    final isBottom = widget.type == CommentTypeEnumValue.short ||
        widget.type != CommentTypeEnumValue.circle ||
        widget.type == CommentTypeEnumValue.infoPromotion;

    return Column(
      children: [
        isBottom ? _buildShortHeader() : const SizedBox.shrink(),
        // SizedBox(
        //     height: 65.w,
        //     width: double.infinity,
        //     child: Column(
        //       crossAxisAlignment: CrossAxisAlignment.start,
        //       children: [
        //         // _buildLine(),
        //         _buildTxtReply(),
        //       ],
        //     ),
        //   ),
        Expanded(
          child: EasyRefresh.builder(
            onRefresh: onRefreshComments,
            onLoad: onLoadComments,
            controller: refreshController,
            childBuilder: (context, physics) => CustomScrollView(
              physics: physics,
              slivers: <Widget>[
                if (widget.type != CommentTypeEnumValue.short &&
                    widget.type != CommentTypeEnumValue.circle)
                  _buildTips().sliverBox,
                if (widget.type != CommentTypeEnumValue.short &&
                    widget.type != CommentTypeEnumValue.circle)
                  _buildAds().sliverBox,
                _buildCommentList(),
              ],
            ),
          ),
        ),
        _buildShortReplyTxt()
      ],
    );
  }
}
